#include "config/global_config.hpp"
#include "common/FileCommon.hpp"
#include "server/connect.hpp"


SystemConfig gSystemConfig;
std::unordered_map<std::string,IbdConfig> gTableConfig;
LockSys gLockSys;
TransactionManager gTrxMgr;
void painInit() {  // 在这里定义
    SetConsoleOutputCP(65001);  // UTF-8
    SetConsoleCP(65001);
    gSystemConfig = loadFromJson<SystemConfig>("system_config.json");

    for (const DataConfig& dataConfig :gSystemConfig.dataConfigs) {
        IbdConfig ibdConfig{};

        ibdConfig.file = std::make_unique<std::fstream>(dataConfig.tablePath,
                                                  std::ios::in | std::ios::out | std::ios::binary);

        FileHeader fileHeader{};
        FileCommon::readTableFileHeader(*ibdConfig.file,fileHeader);
        ibdConfig.fileHeader = fileHeader;

        std::vector<FieldInfo> fieldList(dataConfig.schemaSize);
        FileCommon::readTableFieldList(*ibdConfig.file,fieldList);
        ibdConfig.fieldInfo = fieldList;

        gTableConfig.insert_or_assign(dataConfig.tableName, std::move(ibdConfig));
    }
    // 初始化三大日志
    IbdConfig undoLog{};
    undoLog.file = std::make_unique<std::fstream>(gSystemConfig.undoLogPath,
                                                    std::ios::in | std::ios::out | std::ios::binary | std::ios::app);
    gTableConfig.insert_or_assign(UNDO_LOG,std::move(undoLog));
    // 初始化全局锁
    gLockSys = *new LockSys();
    gTrxMgr = *new TransactionManager();
    MySQLServer server(MYSQL_PORT);
     try {
         server.start();
     } catch (const std::exception& e) {
         std::cerr << "服务器异常: " << e.what() << std::endl;
     }



//    logJsonStruct(systemConfig);
//    SystemConfig systemConfig;
//    systemConfig.dataPath = "d:\\";
//
//    DataConfig dataConfig;
//    dataConfig.tableName = "pixel";
//    dataConfig.tablePath = "D:\\test.ibd";
//    systemConfig.dataConfigs.push_back(dataConfig);
//
//    saveAsJson("D:\\system_config.json",systemConfig);

}

void findDataConfig(const std::string &name,DataConfig &dataConfig){
    for (const DataConfig& config:gSystemConfig.dataConfigs) {
        if(name == config.tableName){
            dataConfig = config;
        }
    }
}